package io.renren.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import dm.jdbc.util.StringUtil;
import io.renren.common.utils.DateUtils;
import io.renren.dto.SendInfoDto;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信公众号推送
 */
@Component
public class WechatMsg {

    /**
     * 获取token
     *
     * @return token
     */
    public static String getToken() throws IOException {
        // 授予形式
        String grant_type = "client_credential";
        //应用ID
        String appid = "wxd433a91dbcfde638";
        //密钥
        String secret = "f296f3be7953f98b94783a6fe46ffd65";
        // 接口地址拼接参数
        String getTokenApi = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + grant_type + "&appid=" + appid + "&secret=" + secret;
        String tokenJsonStr = doGetPost(getTokenApi, "GET", null);
        JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr);
        String token = tokenJson.get("access_token").toString();
        System.out.println("获取到的TOKEN : " + token);
        return token;
    }


    /**
     * 根据 token 和 公众号 Openid 获取 Unionid
     *
     * @param token
     * @param wxopenid
     * @return
     * @throws IOException
     */
    public static String getWxUnionidByWxOpenid(String token, String wxopenid) throws IOException {
        String unionIdUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
        unionIdUrl = unionIdUrl.replace("ACCESS_TOKEN", token);
        unionIdUrl = unionIdUrl.replace("OPENID", wxopenid);

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(unionIdUrl);
        String result = null;
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            result = EntityUtils.toString(response.getEntity(), "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(result);
            return jsonObject.getString("unionid");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     * 发送消息
     */
    public static void SendWeChatMsg(Map<String, Object> paramMap) throws IOException {
        String token = getToken();
        // 接口地址
        String sendMsgApi = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
        System.out.println(doGetPost(sendMsgApi, "POST", paramMap));
    }

    /**
     * 调用接口 post
     *
     * @param apiPath
     */
    public static String doGetPost(String apiPath, String type, Map<String, Object> paramMap) throws IOException {
        OutputStreamWriter out = null;
        InputStream is = null;
        String result = null;
        try {
            URL url = new URL(apiPath);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod(type); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            if (type.equals("POST")) {
                out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
                out.append(JSON.toJSONString(paramMap));
                out.flush();
                out.close();
            }
            // 读取响应
            is = connection.getInputStream();
            int length = (int) connection.getContentLength();// 获取长度
            if (length != -1) {
                byte[] data = new byte[length];
                byte[] temp = new byte[512];
                int readLen = 0;
                int destPos = 0;
                while ((readLen = is.read(temp)) > 0) {
                    System.arraycopy(temp, 0, data, destPos, readLen);
                    destPos += readLen;
                }
                result = new String(data, "UTF-8"); // utf-8编码
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 推送微信公众号-施工完成通知
     */
    public static void send01(String openid,
                              String carNumber,
                              String thing2,
                              String thing5) throws IOException {
        System.out.println("推送微信公众号-施工完成通知");
        //整体参数map
        Map<String, Object> paramMap = new HashMap<>();
        //消息主题显示相关map
        Map<String, Object> dataMap = new HashMap<>();
        //根据自己的模板定义内容和颜色
        dataMap.put("car_number1", new DataEntity(carNumber, "#173177"));
        dataMap.put("thing2", new DataEntity(thing2, "#173177"));
        dataMap.put("thing5", new DataEntity(thing5, "#173177"));
        dataMap.put("time6", new DataEntity(DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"), "#173177"));

        paramMap.put("template_id", "9Z5SXPntyYF2j8Fu6dbCUg-36Aj6Iv-IWM59Uq4TGVA");
        paramMap.put("data", dataMap);
        paramMap.put("touser", openid);
        System.out.println(JSONObject.toJSONString(paramMap));
        SendWeChatMsg(paramMap);
    }

    /**
     * 车辆检测结果通知
     *
     * @param openid
     * @param carNumber
     * @throws IOException
     */
    public static void send02(String openid,
                              String carNumber,
                              String thing7,
                              String thing13) throws IOException {
        System.out.println("______________________");
        System.out.println("推送微信公众号-车辆检测结果通知");
        System.out.println("______________________");
        //整体参数map
        Map<String, Object> paramMap = new HashMap<>();
        //消息主题显示相关map
        Map<String, Object> dataMap = new HashMap<>();
        //根据自己的模板定义内容和颜色
        //        dataMap.put("first", new DataEntity("施工完成通知", "#173177"));
        dataMap.put("car_number2", new DataEntity(carNumber, "#173177"));
        dataMap.put("thing7", new DataEntity(thing7, "#173177"));
        dataMap.put("thing13", new DataEntity(thing13, "#173177"));
        dataMap.put("time5", new DataEntity(DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"), "#173177"));

        //        dataMap.put("remark", new DataEntity("", "#173177"));
        paramMap.put("template_id", "8FCy7hg-QlL7pz_7Ubl3m4yEkWjfjJYIzbLO0VyYcnU");
        paramMap.put("data", dataMap);
        paramMap.put("touser", openid);
        System.out.println(JSONObject.toJSONString(paramMap));
        SendWeChatMsg(paramMap);
    }

    /**
     * 结束洗车通知
     *
     * @param openid
     * @param carNumber
     * @throws IOException
     */
    public static void send03(String openid,
                              String carNumber,
                              String thing4,
                              String time5) throws IOException {
        System.out.println("______________________");
        System.out.println("推送微信公众号-结束洗车通知");
        System.out.println("______________________");
        //整体参数map
        Map<String, Object> paramMap = new HashMap<>();
        //消息主题显示相关map
        Map<String, Object> dataMap = new HashMap<>();
        //根据自己的模板定义内容和颜色
        //        dataMap.put("first", new DataEntity("施工完成通知", "#173177"));
        dataMap.put("car_number9", new DataEntity(carNumber, "#173177"));
        dataMap.put("thing4", new DataEntity(thing4, "#173177"));
        dataMap.put("time5", new DataEntity(DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"), "#173177"));

        //        dataMap.put("remark", new DataEntity("", "#173177"));
        paramMap.put("template_id", "d5SKx5AIcAKplDYdcdoGA3FItPZrJcpEtGjQrmccQYc");
        paramMap.put("data", dataMap);
        paramMap.put("touser", openid);
        System.out.println(JSONObject.toJSONString(paramMap));
        SendWeChatMsg(paramMap);
    }


    /**
     * 服务单确认提醒
     *
     * @param openid
     * @param carNumber
     * @throws IOException
     */
    public static void send04(String openid,
                              String carNumber,
                              String thing17,
                              String amount) throws IOException {
        System.out.println("______________________");
        System.out.println("推送微信公众号-服务单确认提醒");
        System.out.println("______________________");
        //整体参数map
        Map<String, Object> paramMap = new HashMap<>();
        //消息主题显示相关map
        Map<String, Object> dataMap = new HashMap<>();
        //根据自己的模板定义内容和颜色
        //        dataMap.put("first", new DataEntity("施工完成通知", "#173177"));
        dataMap.put("car_number8", new DataEntity(carNumber, "#173177"));
        dataMap.put("thing17", new DataEntity(thing17, "#173177"));
        dataMap.put("amount11", new DataEntity(amount, "#173177"));
        dataMap.put("time9", new DataEntity(DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"), "#173177"));

        //        dataMap.put("remark", new DataEntity("", "#173177"));
        paramMap.put("template_id", "PMu3SSxDDQUBxBkDdt_LCLUh5tZHFmhSCjQ38ewtlPQ");
        paramMap.put("data", dataMap);
        paramMap.put("touser", openid);
        System.out.println(JSONObject.toJSONString(paramMap));
        SendWeChatMsg(paramMap);
    }


    public static void main(String[] args) throws IOException {
        // 转换 unionid
//        String token = getToken();
//        String unionid = getWxUnionidByWxOpenid(token, "olVd4t72_c22aNsrQ_OvFYzTEPNE");
//        System.out.println("Unionid___>:" + unionid);
        // 发消息
//        sendInfoForAddAttendInfo("olVd4t72_c22aNsrQ_OvFYzTEPNE");
    }

    public static void sendMsg(SendInfoDto dto, String wxopenid) {
        try {

            // 1 服务单确认提醒  2 结束洗车通知  3 车辆检测结果通知 4 施工完成通知
            if (dto.getType() == 1) {
                send04(wxopenid, dto.getCarNumber(), dto.getThing17(), dto.getAmount11());
            }
            if (dto.getType() == 2) {
                send03(wxopenid, dto.getCarNumber(), dto.getThing4(), null);
            }
            if (dto.getType() == 3) {
                if (StringUtil.isNotEmpty(dto.getThing7())) {
                    send02(wxopenid, dto.getCarNumber(), dto.getThing7(), dto.getThing13());
                }
            }
            if (dto.getType() == 4) {
                send01(wxopenid, dto.getCarNumber(), dto.getThing2(), dto.getThing5());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}